import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CoreLayout from 'containers/layout'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { getDataSource, getFlagValue, showTeam, getTeamFlag, getPageFlag } from 'services/utils'
import { Form, Input, InputNumber, DatePicker, Divider, Button, Select, Radio, Switch, Row, Col, Tooltip, Icon, message, Card, Popconfirm } from 'antd'
import { protoActions } from 'reduxs'
import _ from 'lodash'
import moment from 'moment'
import 'styles/account.scss'
import { ItemSelect } from '../../../components'

const FormItem = Form.Item
const Option = Select.Option
const TextArea = Input.TextArea
const RadioGroup = Radio.Group
const RadioButton = Radio.Button
const accessFlag = getPageFlag('/proto-tool/send-mail', 'access')
const fullServiceFlag = getPageFlag('/proto-tool/send-mail', 'full-service')

var uuid = 0
var uItems = []

@connect(
  state => ({
    auth                : state.Passport.auth,
    teams               : state.Passport.teams,
    rtsp_key            : state.Passport.rtsp_key,
    postDataPending     : state.Proto.postDataPending,
    postDataError       : state.Proto.postDataError,
    postDataMessage     : state.Proto.postDataMessage,
    postData            : state.Proto.postData,
    postDataProto       : state.Proto.postDataProto,
    srv                 : state.Proto.srv,
    items               : state.Proto.items
  }),
  dispatch => ({
    actions: bindActionCreators({ 
      ...protoActions
    }, dispatch)
  })
)
@Form.create()
export default class SendMail extends PureComponent {

  state = {
    fullService: false
  }

  constructor (props) {
    super(props)
    this._ItemSelect = null
  }

  componentWillMount () {
    this.props.actions.getlist()
  }
  
  componentWillReceiveProps (nextProps) {
    const { postDataError, postDataMessage, postDataProto, postData, rtsp_key } = nextProps
    if (rtsp_key !== this.props.rtsp_key) {
      return
    }
    if (postDataProto === 'send-mail' && postDataError === 0 && this.props.postDataError === -1) {
      this.handleReset()
      message.success('系统邮件已发送！')
    }
  }

  render () {
    const { location, auth, teams, rtsp_key, form, postData, postDataPending, srv, items } = this.props
    const { getFieldDecorator, getFieldValue } = form
    const options = {
      location,
      pageCode: accessFlag.value,
      breadcrumb: [
        { name: '主页', link: '/' },
        { name: '运营工具类' },
        { name: '系统邮件' }
      ],
    }
    /*let PostData = null
    let PostOptions = {}
    if (_.has(postData, 'send-mail')) {
      PostData = postData['send-mail']
      PostOptions = PostData.opts
    }*/
    return (
      <CoreLayout {...options}>
        <Form
          className="ant-advanced-search-form"
          style={{ display: 'flex', justifyContent: 'center', paddingTop: 80 }}
          onSubmit={this.handleSubmit}
          >
          <div style={{ width: 700 }}>
            {!this.state.fullService && (
              <FormItem
                label={(<span style={{ width: 69, display: 'inline-block' }}>收件人</span>)}
                >
                {getFieldDecorator('recId', {
                  rules: [
                    { required: true, message: '请填写玩家ID，多个玩家用空格分隔' }
                  ],
                })(
                    <Input style={{ width: 500 }} placeholder="玩家ID，多个玩家用空格分隔" />
                )}
              </FormItem>
            )}
            {!this.state.fullService && (<Divider dashed />)}
            <FormItem 
              label={(<span style={{ width: 69, display: 'inline-block' }}>邮件标题</span>)}
              >
              {getFieldDecorator('title', {
                rules: [
                  { required: true, message: '请填写邮件标题' }
                ],
              })(
                  <Input style={{ width: 500 }} />
              )}
            </FormItem>
            <FormItem 
              label={(<span style={{ width: 69, display: 'inline-block' }}>邮件正文</span>)}
              >
              {getFieldDecorator('content', {
                rules: [
                  { required: true, message: '请填写邮件正文' }
                ],
              })(
                <TextArea style={{ width: 500 }} rows={8}/>
              )}
            </FormItem>
            <Divider dashed />
            <FormItem 
              label={(<span style={{ width: 80, display: 'inline-block' }}>道具附件</span>)}
              >
              {getFieldDecorator('items', {
                initialValue: []
              })(
                <ItemSelect
                  ref={ref => this._ItemSelect = ref}
                  items={items}
                  //style={{ marginLeft: 95 }}
                  />
              )}
            </FormItem>
            
            <Divider dashed />
            <FormItem 
              label={(<span style={{ width: 80, display: 'inline-block' }}>服务器</span>)}
              >
              {getFieldDecorator('hui', {
                initialValue: false
              })(
                <RadioGroup>
                {_.keys(srv).map((item, i) => {
                  return (
                    <RadioButton key={i} value={[false, true][item]}>{srv[item]}</RadioButton>
                  )
                })}
                </RadioGroup>
              )}
              <span style={{ marginLeft: 40, marginRight: 5 }}>全服发送</span>
              <Switch
                checked={this.state.fullService}
                onChange={() => this.setState({ fullService: !this.state.fullService })}
                disabled={getFlagValue(auth, fullServiceFlag.value, null)}
                />
            </FormItem>
            <Divider dashed />
            <FormItem>
              <Button 
                style={{ marginLeft: 95 }}
                type="primary" 
                htmlType="submit" 
                loading={postDataPending} 
                >
                发送邮件
              </Button>
              <Button 
                style={{ marginLeft: 15 }}
                type="ghost" 
                onClick={this.handleReset}
                >
                重置
              </Button>
            </FormItem>
          </div>
        </Form>
      </CoreLayout>
    )
  }

  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.actions.postData('send-mail', { 
          ...values, 
          recId: _.isEmpty(_.trim(values.recId)) ? _.trim(values.recId) : _.trim(values.recId).split(/\s+/),
          sendName: '系统'
        }, this.props.rtsp_key)
      }
    })
  }

  handleReset = (e) => {
    e && e.preventDefault()
    this.props.form.resetFields()
    this._ItemSelect.resetFields()
  }


  add = () => {
    uuid++
    const keys = this.props.form.getFieldValue('keys')
    const nextKeys = keys.concat(uuid)
    this.props.form.setFieldsValue({
      keys: nextKeys,
    })
    uItems.push({key: uuid, name: undefined, num: 1 })
  }

  remove (k) {
    const keys = this.props.form.getFieldValue('keys')
    this.props.form.setFieldsValue({
      keys: keys.filter(key => key !== k)
    })
    _.remove(uItems, e => e.key === k)
  }

  onChangeSelectItem (k, value) {
    _.find(uItems, {key: k}).num = value
  }
}
